package com.example.myapplication.adapter;

import android.app.AlertDialog;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.database.TodoDatabaseHelper;
import com.example.myapplication.databinding.ListItemBinding;
import com.example.myapplication.model.Todo;

import java.util.List;

public class TodoAdapter extends RecyclerView.Adapter<TodoAdapter.TodoViewHolder> {
    private List<Todo> todoList;
    private TodoDatabaseHelper databaseHelper;
    private Runnable onDataChangedCallback;

    public TodoAdapter(List<Todo> todoList, TodoDatabaseHelper databaseHelper, Runnable onDataChangedCallback) {
        this.todoList = todoList;
        this.databaseHelper = databaseHelper;
        this.onDataChangedCallback = onDataChangedCallback;
    }

    @NonNull
    @Override
    public TodoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 使用 ViewBinding 创建视图绑定
        ListItemBinding binding = ListItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new TodoViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull TodoViewHolder holder, int position) {
        Todo todo = todoList.get(position);

        // 更新任务文本
        holder.binding.contentTv.setText(todo.getTask());

        // 更新复选框和文字状态
        updateViewHolderUI(holder, todo);

        // 避免绑定时触发监听器，移除任何旧的监听器
        holder.binding.checkbox.setOnCheckedChangeListener(null);

        // 手动设置复选框状态（确保与数据一致）
        holder.binding.checkbox.setChecked(todo.isCompleted());

        // 修改任务状态
        holder.binding.checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // 更新数据源
            todo.setCompleted(isChecked);

            // 更新数据库
            databaseHelper.updateTodoStatus(todo.getId(), isChecked);

            // 更新单项视图显示
            updateViewHolderUI(holder, todo);

            // 通知外部刷新数据
            if (onDataChangedCallback != null) {
                onDataChangedCallback.run();
            }
        });

        // 设置长按删除监听器
        holder.itemView.setOnLongClickListener(v -> {
            new AlertDialog.Builder(v.getContext())
                    .setMessage("确定删除该任务吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 删除任务
                        databaseHelper.deleteTodoById(todo.getId());
                        // 通知外部刷新数据
                        if (onDataChangedCallback != null) {
                            onDataChangedCallback.run();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
            return true;
        });
    }

    @Override
    public int getItemCount() {
        return todoList.size();
    }

    // 更新 todoList，并通知 RecyclerView 刷新
    public void updateTodoList(List<Todo> newTodoList) {
        this.todoList = newTodoList;
        notifyDataSetChanged(); // 刷新 RecyclerView
    }

    // 更新单项视图显示
    private void updateViewHolderUI(@NonNull TodoViewHolder holder, Todo todo) {
        if (todo.isCompleted()) {
            holder.binding.contentTv.setTextColor(Color.GRAY);
            holder.binding.contentTv.setPaintFlags(holder.binding.contentTv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            holder.binding.contentTv.setTextColor(Color.BLACK);
            holder.binding.contentTv.setPaintFlags(holder.binding.contentTv.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
        }
    }

    public static class TodoViewHolder extends RecyclerView.ViewHolder {
        ListItemBinding binding;

        public TodoViewHolder(@NonNull ListItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
